﻿using Common.Utility;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Web.Framework;

namespace Web.Filter
{
    public class PermissionFilter : ActionFilterAttribute
    {
        /// <summary>
        /// 验证登录
        /// </summary>
        /// <param name="filterContext"></param>
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            #region 允许匿名
            if (filterContext.ActionDescriptor.FilterDescriptors.Any(x => x.Filter is NoLoginAttribute))
            {
                return;
            }
            #endregion
            if (filterContext.HttpContext.User.Identity.IsAuthenticated == false)
            {
                filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new { controller = "Login", action = "Index", area = "" }));
            }
            else
            {
                if (filterContext.ActionDescriptor.FilterDescriptors.Any(x => x.Filter is NoPermissionAttribute))
                {
                    return;
                }
                string pageurl = filterContext.HttpContext.Request.Path.Value;
                var userrole = (ServiceLocator.Instance as ServiceProvider).GetService<IUserRole>();

                var userInfo = new UserInfo(filterContext.HttpContext);
                var result = userrole.Check(userInfo, pageurl);
                if (!result)
                {
                    filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new { controller = "Home", action = "Error", area = "" }));
                }
            }
        }
    }
}